package com.mvc.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Page;
import com.mvc.model.Notice;
import com.mvc.request.ReqNotice;
import com.mvc.request.ReqPage;
import com.mvc.request.ReturnData;
import com.mvc.response.Code;
import com.mvc.response.RspNotice;
import com.mvc.response.RspPage;
import com.mvc.service.NoticeService;

/***
 * 消息
 * 
 * @author Swer
 * 
 */
public class NoticeServiceImpl implements NoticeService {

	@Override
	public ReturnData<RspPage<RspNotice>> queryPage(ReqPage req) {

		if (req == null) {

			return new ReturnData<RspPage<RspNotice>>(null,
					Code.CODE_PARA_COMPLETE.getCode(),
					Code.CODE_PARA_COMPLETE.getMsg());
		}

		Page<Notice> page = Notice.dao.getPage(req.getNowPage(),
				req.getPageSize());
		RspPage<RspNotice> rspPage = new RspPage<RspNotice>();
		rspPage.setNowPage(req.getNowPage());
		rspPage.setTotalPage(page.getTotalPage());
		rspPage.setList(getList(page.getList()));

		return new ReturnData<RspPage<RspNotice>>(rspPage, 200, "OK");
	}

	private List<RspNotice> getList(List<Notice> list)
	{
		List<RspNotice> data = new ArrayList<>(10);
		if (list != null && !list.isEmpty())
		{
			for (Notice notice : list)
			{
				RspNotice rspNotice = new RspNotice();
				rspNotice.setId(notice.getInt(Notice.TableField.ID));
				rspNotice.setTitle(notice.getStr(Notice.TableField.TITLE));
				rspNotice.setUrl(notice.getStr(Notice.TableField.URL));
				rspNotice.setType(notice.getInt(Notice.TableField.TYPE));
				String content = notice.getStr(Notice.TableField.CONTENT);
				content = content.substring(0, content.length()>50?50: content.length());
				rspNotice.setDesc(content);
				rspNotice.setCreateTime(notice.getDate(Notice.TableField.CREATETIME));
				data.add(rspNotice);
			}
		}
		
		return data;
	}

	@Override
	public ReturnData<String> getInfo(ReqNotice req) {
		Notice notice = Notice.dao.findById(req.getId());
		if (notice == null) {
			return new ReturnData<String>("", 201, "查无此消息公告");
		}
		return new ReturnData<String>(notice.getStr(Notice.TableField.CONTENT),
				200, "OK");
	}
}
